package com.endbd.purchase.manage.type.service.impl;

import com.endbd.feignapi.model.purchase.CBrand;
import com.endbd.feignapi.model.purchase.CType;
import com.endbd.feignapi.util.PageModel;
import com.endbd.purchase.manage.brand.dao.IBrandDao;
import com.endbd.purchase.manage.brand.model.BrandCondition;
import com.endbd.purchase.manage.type.dao.ITypeDao;
import com.endbd.purchase.manage.type.model.TypeCondition;
import com.endbd.purchase.manage.type.service.ITypeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class TypeService implements ITypeService {

    @Autowired
    private ITypeDao typeDao;

    @Autowired
    private IBrandDao brandDao;


    @Override
//    @Transactional(R)
    public PageModel<CType> queryTypePageByCondition(PageModel<CType> pageModel, TypeCondition tcon) {


        int pageNum = pageModel.getPageNum()<=0?1:pageModel.getPageNum();
        int pageSize = pageModel.getPageSize()<=0?5:pageModel.getPageSize();

        PageHelper.startPage(pageNum,pageSize);
        List<CType> types = typeDao.queryTypeCondition(tcon);

        PageInfo<CType> info = new PageInfo<CType>(types);

        pageModel.setPageNum(info.getPageNum());
        pageModel.setPageSize(info.getPageSize());
        pageModel.setTotalPage(info.getPages());
        pageModel.setTotalCount((int)info.getTotal());
        pageModel.setData(types);
        return pageModel;
    }

    @Override
    public void addType(CType type,String brandName) {
        gettype(type,brandName);
        typeDao.addType(type);
    }

    @Override
    public void alterType(CType type,String brandName) {
        gettype(type,brandName);
        typeDao.alterType(type);
    }

    @Override
    public List< String> querytypeName(TypeCondition tcon) {
        List<String> typeName = typeDao.typeName(tcon);
        return typeName;
    }

    @Override
    public void lorType(TypeCondition tcon) {
        if (tcon.getTypeStatus()==1){
            typeDao.logType(tcon.getTypeId());
        }else {
            typeDao.recoveryType(tcon.getTypeId());
        }
    }

    //通过brandName获取brandId并赋值到type中
    public void gettype(CType type,String brandName){
        BrandCondition bcon = new BrandCondition();
        bcon.setBrandName(brandName);
        List<CBrand> cBrands = brandDao.queryBrandCondition(bcon);
        type.setBrandId(cBrands.get(0).getBrandId());
    }
}
